package com.cmz.common.crypto;

import com.cmz.common.api.crypto.Encryptor;
import com.cmz.common.enums.CommonError;
import com.cmz.common.exception.ServiceRuntimeException;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author cmz
 */
public class Md5Encryptor implements Encryptor {

    @Override
    public byte[] encrypt(byte[] bytes) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new ServiceRuntimeException(CommonError.XATSDKCM0000, e);
        }

        return toHex(md.digest(bytes)).getBytes();
    }

    private static String toHex(byte[] input) {
        if (input == null) {
            return null;
        }

        StringBuilder output = new StringBuilder(input.length * 2);
        for (byte anInput : input) {
            int current = anInput & 0xff;
            if (current < 16) {
                output.append("0");
            }
            output.append(Integer.toString(current, 16));
        }

        return output.toString();
    }

}
